﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Transactions;
using System.Text;

namespace IntellectShop.Common
{
	public partial class Schedule : SortedList<DateTime, ScheduleItem>
	{
		public const int MonthOfNearestCourses = 4;

		public int CourseID { get; private set; }

		public Schedule(int courseId)
		{
			this.CourseID = courseId;
		}

		public string GetScheduleItemInMonth(DateTime month)
		{
			var query = from items in this
						where items.Key.Month == month.Month
						select items.Value.EventDate.Day;

			return GetNumericDiapazones(query);
		}

		public static string GetNumericDiapazones(IEnumerable<int> list)
		{
			StringBuilder buf = new StringBuilder();
			int? prevDay = null;
			int curDay = list.FirstOrDefault();
			int startDay = curDay;
			foreach (var day in list)
			{
				curDay = day;
				if (!prevDay.HasValue)
				{
					buf.Append(curDay);
				}

				if (prevDay.HasValue && prevDay.Value != curDay - 1)
				{
					if (startDay == prevDay)
					{
						buf.AppendFormat(", {0}", curDay);
					}
					else
					{
						buf.AppendFormat("-{0}, {1}", prevDay.Value, curDay);
					}

					startDay = curDay;
				}

				prevDay = curDay;
			}

			if (prevDay.HasValue && prevDay.Value != startDay)
			{
				buf.AppendFormat("-{0}", prevDay.Value);
			}

			return buf.ToString();
		}
	}
}
